#include <stdio.h>
#include "game.h"
#include "m3dapp.h"

static CGame* g_activeGame = 0;

static char textBackBuffer[256*256];
static int	textBackBufferCursor;

void clearTextBackBuffer()
{
	memset( textBackBuffer, 0, sizeof(textBackBuffer) );
	textBackBufferCursor = 0;
};

void printToTextBackBuffer( const char* szText )
{
	strcat_s(textBackBuffer, szText);
	textBackBufferCursor += strlen(szText);
	textBackBuffer[textBackBufferCursor] = 0;
};

void drawTextBackBuffer()
{
	textBackBuffer[textBackBufferCursor] = '\0';
	printf("%s", textBackBuffer);
	clearTextBackBuffer();
};

void setupGame( void )
{
	printf("- Creating game object.\n");
	g_activeGame = new CGame();
	g_activeGame->Init();
	uint32_t i=0;
	while( i++ < 100 )
	{
		printf( "- Loading... %i%%\n", i );
	}
	clearTextBackBuffer();
};

void updateGame( float fTimeDelta )
{
	//printf("- Frame update.\n");
	printToTextBackBuffer("- Frame update.\n");
};

void drawGame( float fTimeDelta )
{
	//printf("- Frame render.\n");
	printToTextBackBuffer("- Frame render.\n");
	for( uint32_t z=0; z<g_activeGame->Map.Depth; z++ )
	{
		for( uint32_t x=0; x<g_activeGame->Map.Width; x++ )
		{
			if( g_activeGame->PlayerCharacter.Position		== m3d::SPoint2F( (float)x, (float)z ) )
			{
				textBackBuffer[textBackBufferCursor++] = '@';
			}
			else if(g_activeGame->Map.CellsCharacter[z][x]	!= INVALID_ID)
			{
				textBackBuffer[textBackBufferCursor++] = g_activeGame->Map.CellsCharacter[z][x] + 90;
			}
			else if(g_activeGame->Map.CellsItem[z][x]		!= INVALID_ID) 
			{
				textBackBuffer[textBackBufferCursor++] = g_activeGame->Map.CellsItem[z][x] + 65;
			}
			else
				textBackBuffer[textBackBufferCursor++] = g_activeGame->Map.CellsFloor[z][x];
			//printf("%c", g_activeGame->Map.CellsFloor[z][x]);
		}
		textBackBuffer[textBackBufferCursor++] = '\n';
		//printf("\n");
	}
	textBackBuffer[textBackBufferCursor++] = '\0';
	drawTextBackBuffer();
};

void shutdownGame( void )
{
	printf("- Game shutdown called.\n");
	if( g_activeGame )
		delete( g_activeGame );
	shutdownApp();
};

CGame::CGame( void )
{
	printf("- Game object created.\n");
}

CGame::~CGame( void )
{
	printf("- Game object destroyed.\n");
}

#define MAP_WIDTH 32
#define MAP_DEPTH 24

void CGame::Init( void )
{
	Map.Init( MAP_WIDTH, MAP_DEPTH );
	printf("- Game object initialized.\n");
}
